<?php

namespace app\admin\controller\sta\batch;

use app\admin\model\Depot;
use app\admin\model\Factory;
use app\admin\model\Material as Mmaterial;
use app\admin\model\Mcategory;
use app\common\controller\Backend;
use think\Db;
use think\exception\DbException;
use think\response\Json;
use think\Session;

/**
 * 批次成本汇总管理
 *  todo    --  成本报表03-批次成本汇总表
 * @icon fa fa-circle-o
 */
class Cost extends Backend
{

    /**
     * Cost模型对象
     * @var \app\admin\model\sta\batch\Cost
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\sta\batch\Cost;
        $this->view->assign("statusList", $this->model->getStatusList());
    }


    //  3.1     批次成本汇总,   物料单价-不明  ;   料肉比 不明

    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        //   全部批次为行,  条件是:   批次有出栏

//  TODO:  功能完成后, 需要改为: 查询完成上月的数据后,记录存到表 xxx, 并锁定数据不可修改
//  TODO:  查询条件:  月份,当月可修改;  (可能还会按厂区拆分)
        $infoModel = new \app\admin\model\Batch;
        //  计算月份      *
        //   todo   需要改成可选月份
        //   查询本月数据是随动的,单条记录不可修改.  查询上月数据是已存到表 sta_material 的, 查询当月是即时的
        //   todo    $newdate  需要做成用户选择
        $newdate = date("Y-m-01");          // 月初       todo
        $newdate_31 = date("Y-m-d", strtotime("+1 month", strtotime($newdate) )  );    // 月底
        // 汇总月份
        $this->view->assign("mark", date("ym", strtotime($newdate) )."月" );

        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        // 关联表查询
        $depotList = Depot::getList();
        $factoryList = Factory::getList();
        //$mcategoryList = Mcategory::getList();

//print_r($where);die;
        //  数据行:  物料信息,id 即是  m_info.id
        $list = $infoModel->where($where)
            ->field("*, name as  batch ")
            ->order("id ASC")
            ->paginate($limit);
//echo Db::getLastSql();die;
        foreach($list as &$val){
            //$val['depot_id'] = $depotList[$val['depot_id']];
            //$val['factory_id'] = $factoryList[$val['factory_id']];

            // 计算月份
            $val['createtime'] = $newdate;           //  todo
        }

        // TODO:  如果计算合计,  那么要按当前筛选条件, 进行`不分页` 计算
//print_r($list);die;
        // TODO:  采集对应数据

        // 物料-饲料-id
        // 物料-药品-id
        $siliao_i = Db::name("m_info")->where("mmaterial_id",'in', [1,2] )->field("id")->select();
        $siliao_id =  array_keys( array_column($siliao_i, null, 'id') ) ;
        #$siliao_id = implode(",", array_keys( array_column($siliao_i, null, 'id') ) );

        $yaopin_i = Db::name("m_info")->where("mmaterial_id",'in', [4] )->field("id, name")->select();
        $yaopin_id =  array_keys( array_column($yaopin_i, null, 'id') ) ;
        #$yaopin_id = implode(",", array_keys( array_column($yaopin_i, null, 'id') ) );

//print_r($siliao_id);die;
        foreach($list as &$val){
            $pro_out = Db::name("pro_out")
                ->where(['batch_id'=> $val['id'], 'status'=>'已通过' ])
                ->find();
            $pro_light = Db::name("pro_light")
                ->where(['batch_id'=> $val['id'], 'status'=>'已通过' ])
                ->find();


            $siliao =  Db::name("m_apply")
                ->field("*, sum(num) as bill_num ")
                ->where('batch_id' , 'eq' , $val['id'] )
                ->where('info_id', 'in' , $siliao_id )
                ->where('status', 'eq', '已通过'  )
                ->find();

            $yaopin =  Db::name("m_apply")
                ->field("*, sum(num) as bill_num ")
                ->where('batch_id' , 'eq' , $val['id'] )
                ->where('info_id', 'in' , $yaopin_id )
                ->where('status', 'eq', '已通过'  )
                ->find();

//echo Db::getLastSql();die;
//print_r($siliao);die;
//            $bill_allot = Db::name("m_stockbill")
//                ->field("sum(nums) as bill_num, sum(total_price) as bill_total ")
//                ->where(['info_id'=> $val['id'], 'type'=>'调拨', 'status'=>'已通过' ])
//                ->where('newdate' , 'between', [ $newdate, $newdate_31 ] )
//                ->find();
//
//            $lingyong = Db::name("m_apply")
//                ->field("sum(num) as bill_num ")
//                ->where(['info_id'=> $val['id'], 'status'=>'已通过' ])
//                ->where('createtime' , 'between', [ $newdate, $newdate_31 ] )
//                ->find();
            //echo Db::getLastSql();die;
            // 物料单价,  @wtt   当月录入的价格
            // TODO  次月价格变更后 (加权平均...) ,   重新录入一组数据,
            //  (每月显示一组库存数据, 不叠加上月的数据.  每月结算后,创建下月的一组数据. )

//            $lingyong_unit = Db::name("m_stock")
//                ->field("info_id, price")
//                ->where(['status'=> '已通过' ])
//                ->where('createtime' , 'between', [ $newdate, $newdate_31 ] )
//                ->select();
//            $lingyong_unit = array_column($lingyong_unit, "price", "info_id");


            //print_r($lingyong_unit);die;
//echo Db::getLastSql();die;
            //  TODO  重要  这里暂时没计算加权平均
            $val['a'] = $pro_out ? $pro_out['num'] : 0 ;              // 出栏总数
            $val['b'] = $siliao ? $siliao['bill_num'] * 100 : 0 ;     // 批次饲料费用     todo 寻找单价
            $val['c'] = $yaopin ? $yaopin['bill_num'] * 100 : 0 ;      // 批次药品费用    todo 寻找药品单价

            // 计算 1厂 费用
            $val['out_num'] = $val['a'] ;
            $fy = $this->cal_feiyong($val, $newdate, $val['factory_id'] );

            $val['d'] = $fy['shuidian'] ;   // 水电费用（元）
            $val['e'] = $fy['weixiu'] ;   // 维修维护费用（元）
            $val['f'] = $fy['gongzi'] ;   // 工资（元）
            $val['g'] = $fy['shenghuo'] ;   // 生活费用（元）

            $val['h'] = $pro_light ? $pro_light['zhongtu_update'] * 100 : 0 ;   // 种兔更新费用  todo 寻找种兔单价  ( 加光时填入种兔更新数,来源: 不明 , 出入库: 不明 )

            $val['i'] = number_format($val['b'] + $val['c'] + $val['d'] + $val['e'] + $val['f'] + $val['g'] + $val['h'], 2, '.', '');      // 合计费用

            $val['j'] = $val['a'] ? my_divide($val['i'] , $val['a'], 2) : 0 ;         // 出栏只均成本

            $val['k'] = $pro_out ? $pro_out['every'] : 0;               // 出栏均重

            $val['l'] = my_divide($val['i'] , $val['k']) ;     // 斤成本

            $val['m'] = 0;      // 料肉比

            //  出栏数- 种兔更新数
            $a_z = $val['a'] - ( $pro_light?$pro_light['zhongtu_update']:0 ) ;
//dump($a_z) ; die;
            $val['n'] = $a_z >= 0 ? my_divide(($val['i']-$val['h']) , $a_z) : 'x'  ;   // 不含种兔更新的只均成本         todo 出栏种兔是否包括 种兔更新数 ?

            $val['o'] =  my_divide( ($val['i']-$val['h']) , $val['k'] ) ;   // 不含种兔更新的斤成本

            $val['p'] = my_divide( $fy['shenghuo'] , $val['a'] ) ;   // 单只人工成本     :工资/只数

        }

        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

    // 计算水电,维修, 工资, 生活费
    public function cal_feiyong( $val , $newdate, $factory_id  ){
        $every = ['shuidian' => 0,'weixiu' => 0,'gongzi'=>0,'shenghuo'=>0];
        //出栏年月
//        $newdate = "2023-02-05";
//        $factory_id = 1 ;
        $date = date("Y-m",strtotime($newdate));

        //获取当月出栏的兔子的总数
        $zongshu = Db::name("pro_out")->where("DATE_FORMAT(newdate,'%Y-%m')='{$date}' AND factory_id='". $factory_id ."'")->sum("num");
        //获取当前月份的费用信息
//echo Db::getLastSql();
//print_r($zongshu); die;
//print_r($val); die;
        $feiyong = Db::name("feiyong")->where("DATE_FORMAT(riqi,'%Y-%m')='{$date}' AND factory_id='". $factory_id ."'")->find();
//echo Db::getLastSql();
//print_r($feiyong); die;
        $zongshu = $zongshu <=0 ? 1 : $zongshu ;
        if($feiyong){
            //平均到每只出栏兔子的费用
            $every['shuidian'] = ( $feiyong['shuidian'] / $zongshu );
            $every['weixiu'] = ($feiyong['weixiu'] / $zongshu);
            $every['gongzi'] = ($feiyong['gongzi'] / $zongshu);
            $every['shenghuo'] = ( $feiyong['shenghuo'] / $zongshu);
        }
        //出栏兔子费用统计
        $res['shuidian'] = my_mult( $every['shuidian'] , $val['out_num']);
        $res['weixiu'] = my_mult($every['weixiu'] , $val['out_num']);
        $res['gongzi'] = my_mult($every['gongzi'] , $val['out_num']);
        $res['shenghuo'] = my_mult($every['shenghuo'] , $val['out_num']);

//        echo $feiyong['shuidian'] . ' / ' . $zongshu . ' * ' . $val['out_num']; die;
        return $res ;
    }


    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
   /* public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
//        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
//        $params = [];
//        $admin = Session::get();
//        //厂长，只查看对应厂数据
//        if(!empty($admin['factory_id'])){
//            $params['a.factory_id'] = $admin['factory_id'];
//        }

        //  todo 131
        //  加  “窝均带仔数”   =选留数/选留窝数


//        $list = Db::name("batch")->select() ;


        if('无数据'){
            // 实时统计批次的相关成本
        }else{
            // 统计批次成本后, 结果保存到表 sta_batch_cost
        }

        $list = Db::name("sta_batch_cost")->select() ;

        foreach($list as $k => &$v ){
//            $v['出栏总数'] = 0;
//            $v['批次饲料费用'] = 0;


            $v['id'] = 1;
            $v['depot_id'] = 1;
            $v['batch_id'] = 203300222;
            $v['factory_id'] =  1;
            //

            $v['a'] = 500;
            $v['b'] = 1568.66;
            $v['c'] = 0;
            $v['d'] = 0;
            $v['e'] = 0;
            $v['f'] = 0;
            $v['g'] = 0;
            $v['h'] = 0;
            $v['i'] = 0;
            $v['j'] = 0;
            $v['k'] = 0;
            $v['l'] = 0;
            $v['m'] = 0;
            $v['n'] = 0;
            $v['o'] = 0;
            $v['p'] = 0;
        }


//            ->alias('a')
//            ->join("pro_birth b","a.id = b.batch_id",'left')//产仔
//            ->join("pro_breed br","a.id = br.batch_id",'left')//配种
//            ->join("pro_light l","a.id = l.batch_id",'left')//加光母兔数
//            ->join("pro_milkout mo","a.id = mo.batch_id",'left')//断奶
//            ->join("pro_out o","a.id = o.batch_id",'left')//出栏
//            ->join("pro_select sl","a.id = sl.batch_id",'left')//选留
//            ->join("pro_touch t","a.id = t.batch_id",'left')//摸胎
//            ->join("pro_weight w","a.id = w.batch_id",'left')
//            ->join("group g","a.group_id = g.id",'left')
//            ->join("factory f","a.factory_id = f.id",'left')
//            ->field("a.*,
//            b.newdate as chanzairiqi,b.num as chanzaiwoshu,b.cnum as chanzaizongshu,b.every as wojun,b.rate as chanzailv,b.lnum as chenghuo,b.lrate as wojunhuozai,
//            br.num as peizhongmutu,br.rate as peizhonglv,br.light_num,br.newdate peizhongriqi,
//            l.num as jiaguanshu,l.newdate as jiaguangriqi,
//            mo.newdate as duannairiqi,mo.num as duannaizongshu,mo.cnum as duannaiwoshu,mo.every as duannaichenghuo,mo.rate as duannaijunzhong,
//            o.newdate as chulanriqi,o.num as chulanzongshu,o.nnum as chulanzhongtu,o.bnum as chulanshangpin,o.every as chulanjunzhong,
//            sl.num as xuanliushu,sl.nnum as xuanliuwoshu,
//            t.num as motaishu,t.newdate as motairiqi,t.snum as shoutaishu,t.rate as shoutailv,
//            g.name as group_name,f.name as factory_name
//            ")
//            // ->group("l.batch_id")
//            ->where($where)
//            ->where($params)
//            ->order($sort, $order)
//            ->paginate($limit);

// dump($list);die;
        $result = ['total' => 0, 'rows' => $list ];
        return json($result);
    }*/



    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index_zhouyu()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
       [$where, $sort, $order, $offset, $limit] = $this->buildparams();
       $params = [];
       $admin = Session::get();
       //厂长，只查看对应厂数据
       if(!empty($admin['factory_id'])){
           $params['a.factory_id'] = $admin['factory_id'];
       }

        $list = Db::name("pro_out")
        ->alias('a')
        ->join("factory f","a.factory_id = f.id",'left')
        ->field("a.*,f.name as factory_name")
        ->where($where)
        ->where($params)
        ->order($sort, $order)
        ->paginate($limit);

        
        foreach($list as $key => &$val){
            $every = ['shuidian' => 0,'weixiu' => 0,'gongzi'=>0,'shenghuo'=>0];
            //出栏年月
            $date = date("Y-m",strtotime($val['newdate']));

            //获取当月出栏的兔子的总数
            $zongshu = Db::name("pro_out")->where("DATE_FORMAT(newdate,'%Y-%m')='{$date}' AND factory_id='".$val['factory_id']."'")->sum("num");
            //获取当前月份的费用信息
            
            $feiyong = Db::name("feiyong")->where("DATE_FORMAT(riqi,'%Y-%m')='{$date}' AND factory_id=factory_id")->find();
            if($feiyong){
                //平均到每只出栏兔子的费用
                $every['shuidian'] = $feiyong['shuidian'] / $zongshu;
                $every['weixiu'] = $feiyong['weixiu'] / $zongshu;
                $every['gongzi'] = $feiyong['gongzi'] / $zongshu;
                $every['shenghuo'] = $feiyong['shenghuo'] / $zongshu;
            }
            //出栏兔子费用统计
            $val['shuidian'] = $every['shuidian'] * $val['num'];
            $val['weixiu'] = $every['weixiu'] * $val['num'];
            $val['gongzi'] = $every['gongzi'] * $val['num'];
            $val['shenghuo'] = $every['shenghuo'] * $val['num'];
        }


        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }


}
